/*
 * @Author: silence
 * @Date: 2023-07-04 15:10:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-01-04 10:59:06
 * @Description: 电站控制器
 */

import 'package:ems_neutral_app/config/AppInfo.dart';
import 'package:ems_neutral_app/entities/PowerStationEntity.dart';
import 'package:ems_neutral_app/entities/UserEntity.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/eventBus/eventBus.dart';
import 'package:ems_neutral_app/utils/string/StringConstant.dart';
import 'package:ems_neutral_app/utils/toast/SilToastExtends.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../api/ApiUtils.dart';
import '../../../api/request/PowerStationRequest.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../entities/DeviceEntity.dart';

class PowerStationController extends GetxController {
  /// 当前电站的信息
  Rx<PowerStationEntity> powerStationEntity = PowerStationEntity().obs;

  /// 我的电站列表
  List<DeviceEntity> myPowerStationList = [];
  RxList myPowerStationNameList = [].obs;

  /// 电站设置信息
  RxMap<String, dynamic> powerStationSetInfo = RxMap<String, dynamic>({
    "powerId": 0,
    "dischargeLowerLimit": 0,
    "automaticSettings": 0,
    "moneyType": "CNY",
    "isPayPower": 0,
    "usePowerSet": 1,
    "eybond_ctrl_118": "0000",
    "powerPrice": 0.0,
    "powerSet": 0,
    "eybond_ctrl_119": "0000",
    "eybond_ctrl_116": "0000",
    "eybond_ctrl_117": "0000",
    "eybond_ctrl_121": "0000",
    "eybond_ctrl_122": "0000",
    "eybond_ctrl_112": 0,
    "eybond_ctrl_123": "0000",
    "moneyUnit": "￥",
    "is_as": false,
    "eybond_ctrl_120": "0000",
    "isH": true,
    "isCheckSoc": 0,
  });

  /// 最新电价
  RxMap latestElectricityPriceMap = RxMap({
    "categories": [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "23"
    ],
    "series": [],
  });

  /// 获取电站详情
  powerStationDetail(
      {required BuildContext context,
      required String? deviceId,
      Function(dynamic)? successHandler,
      bool showLoading = false}) async {
    if (SilTools.stringIsEmpty(deviceId)) {
      print('数采器id不能为空');
      return;
    }

    apiShow(context, api: api_power_station_info(deviceId: deviceId!),
        success: (res) {
      if (successHandler != null) successHandler(res);
      this.powerStationEntity.value = res.data;

      /// 高压机型、思道尔机型
      if (this.powerStationEntity.value.equipmentSelection == '1' ||
          this.powerStationEntity.value.stationType == '3') {
        powerStationTemperatureDetail(
          context: context,
          deviceId: deviceId,
          successHandler: successHandler,
        );
      }

      /// 全局保存当前电站的类型
      AppInfo.stationType = this.powerStationEntity.value.stationType;
    }, showLoading: showLoading);
  }

  /// 获取电站温度，余额信息
  powerStationTemperatureDetail({
    required BuildContext context,
    required String? deviceId,
    Function(dynamic)? successHandler,
  }) {
    if (SilTools.stringIsEmpty(deviceId)) {
      print('数采器id不能为空');
      return;
    }

    apiShow(context, api: api_power_station_temperature(deviceId: deviceId!),
        success: (res) {
      /// 合并电站信息
      PowerStationEntity entity = res.data;
      PowerStationEntity powerStationEntity = this.powerStationEntity.value;
      powerStationEntity.ambient_temperature = entity.ambient_temperature;
      powerStationEntity.bms_temperature = entity.bms_temperature;
      powerStationEntity.dcdc_temperature = entity.dcdc_temperature;
      powerStationEntity.inverter_temperature = entity.inverter_temperature;
      powerStationEntity.pv_one = entity.pv_one;
      powerStationEntity.pv_two = entity.pv_two;
      powerStationEntity.pv_two_current = entity.pv_two_current;
      powerStationEntity.electricityConsumption = entity.electricityConsumption;
      powerStationEntity.electricityCost = entity.electricityCost;
      entity = powerStationEntity;

      /// 更新电站信息，此处更新使用'vulue='无效，需要使用update
      this.powerStationEntity.update((val) {
        val = entity;
      });
      if (successHandler != null) successHandler(res);
    }, showLoading: false, showErrorToast: false);
  }

  /// 获取我的电站列表
  /// 是否需要ApiShow进行预处理
  getPowerStationList(
    BuildContext context, {
    bool apiShowHandler = true,
    Function(dynamic)? successHandler,
  }) {
    if (apiShowHandler == false) {
      return api_power_station_my_list();
    }

    apiShow(context, api: api_power_station_my_list(), success: (res) {
      if (successHandler != null) successHandler(res);
      this.myPowerStationList = res.data;
      this.myPowerStationNameList.value =
          this.myPowerStationList.map((e) => e.psName).toList();
    }, showLoading: false);
  }

  /// 切换电站
  /// powerRecordId 电站id
  changePowerStation(
    BuildContext context, {
    String? powerRecordId,
    String? userId,
    Function(dynamic)? successHandler,
  }) {
    if (SilTools.stringIsEmpty(powerRecordId)) {
      print('数采器id不能为空');
      return;
    }

    apiShow(context,
        api: api_power_station_change(
            powerRecordId: powerRecordId!,
            userId: UserBlocTool.userEntity?.id), success: (res) {
      // 保存选择的设备
      UserEntity? userEntity = UserBlocTool.userEntity;
      if (userEntity != null) {
        userEntity.powerRecordId = powerRecordId;
        UserBlocTool.update(context, userEntity);
      }

      // 更换成功
      bus.emit(StringConstant.SelectDeviceChange);
      if (successHandler != null) successHandler(res);
    }, showLoading: false);
  }

  /// 获取电站设置信息
  getPowerStationSetInfo(
    BuildContext context, {
    bool showLoading = false,
    Function(dynamic)? successHandler,
  }) {
    String? powerRecordId = UserBlocTool.userEntity?.powerRecordId;
    if (SilTools.stringIsEmpty(powerRecordId)) {
      print('数采器id不能为空');
      return;
    }

    apiShow(context,
        api: api_power_station_set_info(powerRecordId: powerRecordId!),
        success: (res) {
      Map map = res.data as Map;
      this.powerStationSetInfo.updateAll((key, value) => map[key]);
      if (successHandler != null) successHandler(map);
    }, showLoading: showLoading);
  }

  /// 货币类型
  List<String> getMoneyTypeList() {
    return ['EUR', 'CNY', 'CZK', 'CAD', 'EEK', 'GBP', 'HUF', 'RUB', 'USD'];
  }

  /// 用电模式
  List<String> getUsePowerModeList() {
    return ['SBU', 'SUB', 'UTI', 'SOL']; //KEY 从1开始对应
  }

  /// 获取最新电价
  getLatestElectricityPrice(
    BuildContext context, {
    Function(dynamic)? successHandler,
  }) {
    apiShow(context, api: api_latest_electricity_price(), success: (res) {
      if (successHandler != null) successHandler(res);
      Map map = res.data as Map;
      this.latestElectricityPriceMap.update('series', (value) => map['series']);
      // this.latestElectricityPriceMap = res.data;
    }, showLoading: false);
  }

  /// 削峰填谷-智能获取充放电时间段
  getAutoPeakLoadShifting(
    BuildContext context, {
    Function(dynamic)? successHandler,
  }) {
    apiShow(context, api: api_auto_peak_load_shifting(), success: (res) {
      if (successHandler != null) successHandler(res);
      Map<String, dynamic> priceMap = Map();
      for (int index = 0; index < res.data.length; index++) {
        Map element = res.data[index];
        if (index == 0) {
          if (element.containsKey('chargeStart'))
            priceMap['eybond_ctrl_116'] = element['chargeStart'];

          if (element.containsKey('chargeEnd'))
            priceMap['eybond_ctrl_117'] = element['chargeEnd'];

          if (element.containsKey('dischargeStart'))
            priceMap['eybond_ctrl_118'] = element['dischargeStart'];

          if (element.containsKey('dischargeEnd'))
            priceMap['eybond_ctrl_119'] = element['dischargeEnd'];
        } else if (index == 1) {
          if (element.containsKey('chargeStart'))
            priceMap['eybond_ctrl_120'] = element['chargeStart'];

          if (element.containsKey('chargeEnd'))
            priceMap['eybond_ctrl_121'] = element['chargeEnd'];

          if (element.containsKey('dischargeStart'))
            priceMap['eybond_ctrl_122'] = element['dischargeStart'];

          if (element.containsKey('dischargeEnd'))
            priceMap['eybond_ctrl_123'] = element['dischargeEnd'];
        }
      }

      if (priceMap.isNotEmpty) {
        this.powerStationSetInfo.addAll(priceMap);
      }
    }, showLoading: false);
  }

  /// 保存电站设置
  savePowerStationSet(
    BuildContext context, {
    Function(dynamic)? successHandler,
  }) {
    String? message;

    // 判断当前电站是否在线，如果不在线不允许用户设置
    String ps_name = this.powerStationEntity.value.ps_name ?? "";
    if (ps_name.contains('offline')) {
      message = LangOf(context)?.power_setting?.offline_prompt;
      ;
    }

    // 如果是削峰填谷需要判断时间设置
    if (this.powerStationSetInfo['eybond_ctrl_112'] == 1) {
      if (!checkPeekDataTime()) {
        message = LangOf(context)?.common?.peekShift_err;
      }
    }

    // 电价设置
    String powerPrice = '${this.powerStationSetInfo['powerPrice']}';
    if (SilTools.stringIsEmpty(powerPrice) || powerPrice == '') {
      message = LangOf(context)?.common?.electricity_noZero;
    }

    if (message != null) {
      // 设置有误
      SilToast.show(message);
      return;
    }

    String? alertTitle = LangOf(context)?.power_setting?.editpopTitle;
    String? alertContent = LangOf(context)?.power_setting?.editpop_desc;
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            content: alertContent,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(context,
          api: api_power_station_set_save(paramMap: this.powerStationSetInfo),
          success: (res) {
        if (successHandler != null) successHandler(res);
      }, showLoading: true);
    });
  }

  // 检测削峰填谷时间设置 开始时间不能小于结束时间
  bool checkPeekDataTime() {
    bool flag = false;

    bool flag1 = (this.powerStationSetInfo['eybond_ctrl_116'] == "0000" &&
            this.powerStationSetInfo['eybond_ctrl_117'] == "0000")
        ? true
        : int.parse(this.powerStationSetInfo['eybond_ctrl_116']) <
                int.parse(this.powerStationSetInfo['eybond_ctrl_117'])
            ? true
            : false;

    bool flag2 = (this.powerStationSetInfo['eybond_ctrl_118'] == "0000" &&
            this.powerStationSetInfo['eybond_ctrl_119'] == "0000")
        ? true
        : int.parse(this.powerStationSetInfo['eybond_ctrl_118']) <
                int.parse(this.powerStationSetInfo['eybond_ctrl_119'])
            ? true
            : false;
    bool flag3 = (this.powerStationSetInfo['eybond_ctrl_120'] == "0000" &&
            this.powerStationSetInfo['eybond_ctrl_121'] == "0000")
        ? true
        : int.parse(this.powerStationSetInfo['eybond_ctrl_120']) <
                int.parse(this.powerStationSetInfo['eybond_ctrl_121'])
            ? true
            : false;
    bool flag4 = (this.powerStationSetInfo['eybond_ctrl_122'] == "0000" &&
            this.powerStationSetInfo['eybond_ctrl_123'] == "0000")
        ? true
        : int.parse(this.powerStationSetInfo['eybond_ctrl_122']) <
                int.parse(this.powerStationSetInfo['eybond_ctrl_123'])
            ? true
            : false;

    if (flag1 && flag2 && flag3 && flag4) {
      return true;
    }
    return flag;
  }

  /// 删除电站
  requestPowerStationDelete({
    required BuildContext context,
    required String? deviceId,
    Function(dynamic)? successHandler,
  }) {
    String? alertTitle = LangOf(context)?.userDz_setting?.delete;
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(context, api: api_power_station_del(deveiceId: deviceId!),
          success: (res) {
        SilToastExtends.toastMsg(
            LangOf(context)?.userDz_setting?.deleteSuccess);

        /// 电站数量放生了变化
        bus.emit(StringConstant.PowerStationsNumChange);
        if (successHandler != null) successHandler(res);
      }, showLoading: true);
    });
  }

  /// 给电站重新命名
  requestPowerStationRename({
    required BuildContext context,
    required String? name,
    required String psId,
    Function(dynamic)? successHandler,
    dynamic Function()? failure,
  }) {
    /// 名称不为空
    if (SilTools.stringIsEmpty(name)) {
      SilToastExtends.toastMsg(LangOf(context)?.userDz_setting?.enterName);
      return;
    }

    String? alertTitle = LangOf(context)?.userDz_setting?.modifications;
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            title: alertTitle,
            cancelButtonTitle: alertCancelTitle,
            confrimButtonTitle: alertConfirmTitle), confrimFunc: () {
      apiShow(
        context,
        api: api_power_station_edit(psName: name!, psId: psId),
        success: (res) {
          SilToastExtends.toastMsg(LangOf(context)?.common?.edit_success);
          if (successHandler != null) successHandler(res);
        },
        showLoading: true,
        failure: (result) {
          if (failure != null) failure();
          SilToast.show(result.message);
        },
      );
    }, cancelFunc: () {
      if (failure != null) failure();
    });
  }
}
